package com.ntanh.mealplanner.main.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.ntanh.mealplanner.base.model.BaseEntity;
import com.ntanh.mealplanner.main.objects.Meal;

/**
 * Created by Anh Nguyen on 2/27/2015.
 */
public class BaseDao {

    protected SQLiteDatabase database;
    protected DataBaseHelper dbHelper;
    protected Context mContext;

    protected final String WHERE_ID_EQUALS = BaseEntity.ID + " =?";

    public BaseDao(Context context) {
        this.mContext = context;
        dbHelper = DataBaseHelper.getHelper(mContext);
        open();
    }

    public void open() throws SQLException {
        if (dbHelper == null)
            dbHelper = DataBaseHelper.getHelper(mContext);
        database = dbHelper.getWritableDatabase();
    }

    public boolean save(BaseEntity entity) {
        ContentValues values = new ContentValues();
        entity.toContentValue(values, true);
        int id = (int) database.insert(entity.getTableName(), null, values);
        if (id > -1) {
            entity.setId(id);
            return true;
        }
        return false;
    }

    public long update(BaseEntity entity) {
        ContentValues values = new ContentValues();
        entity.toContentValue(values, true);

        long result = database.update(entity.getTableName(), values,
                WHERE_ID_EQUALS,
                new String[]{String.valueOf(entity.getId())});
        Log.d("Update Result:", "=" + result);
        return result;
    }

    public long delete(BaseEntity entity) {
        long result = database.delete(entity.getTableName(),
                WHERE_ID_EQUALS,
                new String[]{String.valueOf(entity.getId())});
        Log.d("Delete Result:", "=" + result);
        return result;
    }

	/*public void close() {
        dbHelper.close();
		database = null;
	}*/
}
